const app = getApp()

Page({
  data: {
    prompt: '',
    Base: '', //库路径
    defaultImg: {},
    index_notice: {}, //公告
    goods_platform_list: {}, //标签板块
    block_list: {}, //楼层板块
    coupon_list: {}, //优惠券
    discount_list: {}, //限时折扣
    current_time: 0, //当前时间
    timer_array: {}, //限时折扣计时
    search_text: '', //搜索内容
    userInfo: {},
    imageList:{},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    //轮播图属性
    imgUrls: [
      {
         'adv_image': '/images/index/waplunbo.png'
      },
      {
        'adv_image': '/images/index/waplunbo.png'
      },
      {
        'adv_image': '/images/index/waplunbo.png'
      },
    ],
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    circular: true,
    indicatorColor: '#AAA',
    indicatorActiveColor: '#FFF',
    swiperHeight: 153,
    sBuy: 0,
    animation: '',
    goods_info: {}, //商品详情
    spec_list: {}, //规格列表
    attr_value_items_format: '', //选中规格组
    sku_id: 0, //选中规格
    sku_info: {}, //选中规格信息
    stock: 0, //选中规格库存
    promote_price: 0.00, //选中规格价格
    goodsNum: 1, //购买数量
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    let that = this;
  },
  onShow: function(){
    let that = this;
    let defaultImg = app.globalData.defaultImg;
    let siteBaseUrl = app.globalData.siteBaseUrl;
    let timeArray = {};

    app.sendRequest({
      url: 'api.php?s=index/getIndexData',
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        
        let code = res.code;
        let indicatorDots = true;
        if (code == 0) {
          let data = res.data;
          //当前时间初始化
          let current_time = data.current_time;
          that.setData({
            current_time: current_time
          })

          //广告轮播初始化
          if (data.adv_list.adv_index.adv_list.length == 1) {
            indicatorDots = false;
          }

          //优惠券初始化
          for (let index in data.coupon_list){
            data.coupon_list[index].status = 1;
          }

          //限时折扣初始化
          let discount_list = data.discount_list.data;
          for (let index in discount_list){
            timeArray[index] = {};
            timeArray[index].end = 0;
            timeArray[index].end_time = discount_list[index].end_time;
            that.timing(that, timeArray, index);
          }
          
          that.setData({
            Base: siteBaseUrl,
            defaultImg: defaultImg,
            indicatorDots: indicatorDots,
            imgUrls: data.adv_list.adv_index.adv_list,
            index_notice: data.notice,
            goods_platform_list: data.goods_platform_list,
            block_list: data.block_list,
            coupon_list: data.coupon_list,
            discount_list: discount_list
          });
        }
        console.log(res);
      }
    })
  },

  /**
   * 商品楼层图片加载失败
   */
  errorBlockImg: function(e){
    let that = this;
    let index = e.currentTarget.dataset.index;
    let key = e.currentTarget.dataset.key;
    let block_list = that.data.block_list;
    let defaultImg = that.data.defaultImg;
    let parm = {};

    if (defaultImg.is_use == 1){
      let parm_key = "block_list[" + index + "].goods_list[" + key + "].pic_cover_small";
      parm[parm_key] = defaultImg.value.default_goods_img;
      that.setData(parm);
    }
  },

  /**
   * 限时折扣图片加载失败
   */
  errorDiscountImg: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let discount_list = that.data.discount_list;
    let defaultImg = that.data.defaultImg;
    let parm = {};

    if (defaultImg.is_use == 1) {
      let parm_key = "discount_list[" + index + "].picture.pic_cover_small";
      parm[parm_key] = defaultImg.value.default_goods_img;
      that.setData(parm);
    }
  },

  /**
   * 页面跳转
   */
  listClick: function(event) {
    var url = event.currentTarget.dataset.url;
    wx.navigateTo({
      url: '/pages'+url,
    })
  },

  tabBar: function(event) {
    var url = event.currentTarget.dataset.url;
    wx.switchTab({
      url: '/pages' + url,
    })
  },

  /**
   * 输入框绑定事件
   */
  searchInput: function(event){
    var search_text = event.detail.value;
    this.setData({
      search_text: search_text
    })
  },

  /**
  * 购买弹框(动画效果未实现)
  */
  sBuyShow: function (event) {
    let that = this;
    
    let goods_id = event.currentTarget.dataset.id;
    let attr_value_items_format = '';
    let promote_price = 0.00;

    app.sendRequest({
      url: 'api.php?s=goods/goodsDetail',
      data: {
        goods_id: goods_id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      success: function (res) {
        let code = res.code;
        if (code == 0) {
          let data = res.data;
          that.setData({
            goods_info: data,
          });
          let sku_info = that.data.sku_info;//选中规格信息
          let sku_id = that.data.sku_id; //选中规格
          let attr_value_items = {}; //规格组
          let stock = 0; //库存
          //规格默认选中
          for (let i = 0; i < data.spec_list.length; i++) {
            for (let l = 0; l < data.spec_list[i].value.length; l++) {
              if (l == 0) {
                data.spec_list[i].value[l]['status'] = 1;
                attr_value_items[i] = data.spec_list[i].value[l].spec_id + ':' + data.spec_list[i].value[l].spec_value_id;
                attr_value_items.length = i + 1;
              } else {
                data.spec_list[i].value[l]['status'] = 0;
              }
            }
          }

          //规格组、库存判断
          for (let i = 0; i < data.sku_list.length; i++) {
            let count = 1;
            for (let l = 0; l < attr_value_items.length; l++) {
              if (data.sku_list[i].attr_value_items.indexOf(attr_value_items[l]) == -1) {
                count = 0;
              }
            }
            if (count == 1) {
              attr_value_items_format = data.sku_list[i].attr_value_items_format;
              sku_id = data.sku_list[i].sku_id;
              promote_price = data.sku_list[i].promote_price;
              stock = data.sku_list[i].stock;
              sku_info = data.sku_list[i];
            }
          }

          that.setData({
            spec_list: data.spec_list,
            sku_id: sku_id,
            attr_value_items_format: attr_value_items_format,
            promote_price: promote_price,
            stock: stock,
            sku_info: sku_info
          })

          let animation = wx.createAnimation({
            duration: 3000,
            timingFunction: 'ease-in',
            transformOrigin: "50% 50% 0",
            delay: 0
          })
          animation.opacity(1).translateX(-100).step();
          that.animation = animation;
          that.setData({
            sBuy: 1,
            animation: that.animation.export()
          })
        }
      }
    })
  },

  /**
   * 关闭弹框
   */
  sBuyClose: function (event) {
    this.setData({
      sBuy: 0,
    })
  },

  /**
   * sku选中
   */
  skuSelect: function (event) {
    let that = this;
    let key = event.currentTarget.dataset.key;
    let k = event.currentTarget.dataset.k;
    let goods_info = that.data.goods_info;
    let arr = that.data.spec_list;
    let stock = that.data.stock;
    let sku_id = that.data.sku_id;
    let attr_value_items_format = that.data.attr_value_items_format;
    let promote_price = that.data.promote_price;
    let attr_value_items = {};
    let sku_info = that.data.sku_info;

    for (let i = 0; i < arr[key].value.length; i++) {
      arr[key].value[i].status = 0;
    }
    arr[key].value[k].status = 1;
    //拼合规格组
    for (let i = 0; i < arr.length; i++) {
      for (let l = 0; l < arr[i].value.length; l++) {
        if (arr[i].value[l]['status'] == 1) {
          attr_value_items[i] = arr[i].value[l].spec_id + ':' + arr[i].value[l].spec_value_id;
          attr_value_items.length = i + 1;
        }
      }
    }
    //规格组、库存判断
    for (let i = 0; i < goods_info.sku_list.length; i++) {
      let count = 1;
      for (let l = 0; l < attr_value_items.length; l++) {
        if (goods_info.sku_list[i].attr_value_items.indexOf(attr_value_items[l]) == -1) {
          count = 0;
        }
      }
      if (count == 1) {
        sku_id = goods_info.sku_list[i].sku_id;
        attr_value_items_format = goods_info.sku_list[i].attr_value_items_format;
        promote_price = goods_info.sku_list[i].promote_price;
        stock = goods_info.sku_list[i].stock;
        sku_info = goods_info.sku_list[i];
      }
    }
    that.setData({
      spec_list: arr,
      sku_id: sku_id,
      attr_value_items_format: attr_value_items_format,
      promote_price: promote_price,
      stock: stock,
      sku_info: sku_info
    })
  },

  /**
   * 商品数量调节
   */
  goodsNumAdjust: function (event) {
    let type = event.currentTarget.dataset.type;
    let num = this.data.goodsNum;
    let numCount = this.data.stock;

    if (type == 'add' && numCount > 0) {
      num++;
      if (num > numCount) {
        num = numCount;
      }
    } else if (type == 'minus' && numCount > 0) {
      num--;
      if (num <= 0) {
        num = 1;
      }
    } else {
      num = 1;
    }
    this.setData({
      goodsNum: num
    })
  },

  /**
   * 数量调节检测
   */
  goodsNumAdjustCheck: function (event) {
    let val = event.detail.value;
    let numCount = this.data.stock;
    if (val > numCount) {
      return numCount;
    } else if (val < 0) {
      return 0;
    }
  },

  /**
   * 加入购物车
   */
  addCart: function (event) {
    let that = this;

    let cart_detail = {
      shop_id: 0,
      shop_name: 'Niushop开源商城',
      trueId: that.data.goods_info.goods_id,
      goods_name: that.data.goods_info.goods_name,
      count: that.data.goodsNum,
      select_skuid: that.data.sku_id,
      select_skuName: that.data.sku_info.sku_name,
      price: that.data.promote_price,
      cost_price: that.data.sku_info.cost_price,
      picture: that.data.goods_info.picture
    };
    cart_detail = JSON.stringify(cart_detail);

    app.sendRequest({
      url: 'api.php?s=goods/addCart',
      data: {
        cart_detail: cart_detail,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: "POST",
      success: function (res) {
        let code = res.data.code;
        if (code > 0) {
          app.showBox(that, '加入购物车成功')
          that.setData({
            sBuy: 0
          })
        }else{
          app.showBox(that, '加入购物车失败')
        }
      }
    });
  },

  /**
   * 空库存
   */
  nullStock: function () {
    let that = this;
    app.showBox(that, '商品已售馨');
  },

  /**
   * 领取优惠券
   */
  toReceivePopup: function (e) {
    let that = this;
    let coupon_type_id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    let flag = true;
    let status = 1;


    if (flag) {
      app.sendRequest({
        url: 'api.php?s=goods/receiveGoodsCoupon',
        data: {
          coupon_type_id: coupon_type_id
        },
        success: function (res) {
          let code = res.code;
          let data = res.data;

          if (code == 0) {
            if (data > 0) {
              app.showBox(that, '领取成功');
            } else if (data == -2011) {
              app.showBox(that, '来迟了，已经领完了');
              status = 0;
            } else if (data == -2019) {
              app.showBox(that, '领取已达到上限');
              status = 0;
            } else {
              app.showBox(that, '未获取到优惠券信息');
              status = 0;
            }
            let d = {};
            let key = "coupon_list[" + index + "].status";
            d[key] = 0;

            that.setData(d);
          }
        }
      });
    }

    if (!flag) {
      let d = {};
      let key = "coupon_list[" + index + "].status";
      d[key] = 0;

      that.setData(d);
    }
  },

  /**
   * 计时
   */
  timing: function (that, timer_array, index) {
    let current_time = that.data.current_time;
    let count_second = (timer_array[index].end_time * 1000 - current_time) / 1000;
    //首次加载
    if (count_second > 0) {
      count_second--;
      //时间计算
      let day = Math.floor((count_second / 3600) / 24);
      let hour = Math.floor((count_second / 3600) % 24);
      let minute = Math.floor((count_second / 60) % 60);
      let second = Math.floor(count_second % 60);
      //赋值
      timer_array[index].day    = day;
      timer_array[index].hour = hour;
      timer_array[index].minute = minute;
      timer_array[index].second = second;
      timer_array[index].end = 0;

      that.setData({
        timer_array: timer_array
      })
    } else {
      timer_array[index].end = 1;

      that.setData({
        timer_array: timer_array
      })
    }
    //开始计时
    let timer = setInterval(function () {
      if (count_second > 0) {
        count_second--;
        //时间计算
        let day = Math.floor((count_second / 3600) / 24);
        let hour = Math.floor((count_second / 3600) % 24);
        let minute = Math.floor((count_second / 60) % 60);
        let second = Math.floor(count_second % 60);
        //赋值
        timer_array[index].day = day;
        timer_array[index].hour = parseInt(hour) < 10 ? 0 + '' + hour : hour ;
        timer_array[index].minute = parseInt(minute) < 10 ? 0 + '' + minute : minute;;
        timer_array[index].second = parseInt(second) < 10 ? 0 + '' + second : second;;
        timer_array[index].end = 0;

        that.setData({
          timer_array: timer_array
        })
      } else {
        timer_array[index].end = 1;

        that.setData({
          timer_array: timer_array
        })
        
        clearInterval(timer);
      }
    }, 1000)
  },
})
